#Anaconda/envs/pyqtenv python
# -*- coding: utf-8 -*-
'''
@File    :   DevNIC.py
@Time    :   2024/12/24 16:19
@Author  :   CRC1109 
@Version :   1.0
@Desc    :   Built in PyQt5
             虚拟NIC设备, 功能需要
             - 实现信令互传
'''

from Netterminal.Sources.Device.DevBase import DevBase
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QByteArray,Qt,QDateTime
from PyQt5.QtWidgets import QLineEdit,QPushButton,QTextEdit,QTextBrowser
from PyQt5.QtGui import QTextCursor, QTextBlockFormat
from PyQt5.QtNetwork import QUdpSocket, QHostAddress, QAbstractSocket

class DevNIC(DevBase):
    def __init__(self, name: str ,**kwargs):
        super(DevNIC,self).__init__(name)
        self.UdpSocket = QUdpSocket()

        self.register(**kwargs)

    def register(self, **kwargs):
       self.portSendlineEdit:QLineEdit = kwargs.get('portSendlineEdit') 
       self.portRecvlineEdit:QLineEdit = kwargs.get('portRecvlineEdit')
       self.qTextbrowser:QTextBrowser = kwargs.get('qTextbrowser')

    def ready(self):
        self.portSend = "10086"
        self.portRecv = "10086"
        self.UdpSocket.readyRead.connect(self.recvData)

    def UdpOpenListen(self):
        print ("udp try to open port: " + self.portRecv)
        self.UdpSocket.bind(QHostAddress(QHostAddress.SpecialAddress.Any), int(self.portRecv), QAbstractSocket.BindFlag.ShareAddress)

    def UdpCloseListen(self):
        print ("udp try to close port: " + self.portRecv)
        self.UdpSocket.close()

    #格式化字符串org，在相应的间隔插入“ch”
    def formatString(self, org:str, n = 2, ch:str = " "):
        size:int = len(org)
        space:int = round(size*1.0/n+0.5)-1
        if space <= 0:
            return
        pos = n
        for i in range(space):
            org = org[:pos] + ch + org[pos:]
            pos += (n+3)
        return org

     #字符串写入浏览框
    def writeAppend(self, text:str, alignment:Qt.AlignmentFlag):
        self.formatString(text, 30, "\n")
        textList:list = text.split("\n")
        for i in range(len(textList)):
            self.qTextbrowser.append(textList[i])
            storeCursorPos:QTextCursor = self.qTextbrowser.textCursor() #当前光标位置
            textBlockFormat:QTextBlockFormat = storeCursorPos.blockFormat()#格式信息
            textBlockFormat.setAlignment(alignment)
            storeCursorPos.mergeBlockFormat(textBlockFormat)
            self.qTextbrowser.setTextCursor(storeCursorPos) 

    #覆盖
    def writeOverLine(self, text:str, alignment:Qt.AlignmentFlag):
        storeCursorPos:QTextCursor = self.qTextbrowser.textCursor()
        storeCursorPos.select(storeCursorPos.SelectionType.LineUnderCursor)
        storeCursorPos.removeSelectedText()
        self.qTextbrowser.moveCursor(storeCursorPos.MoveOperation.StartOfLine,storeCursorPos.MoveMode.MoveAnchor)
        self.qTextbrowser.insertPlainText(text)

        textBlockFormat:QTextBlockFormat = storeCursorPos.blockFormat()
        textBlockFormat.setAlignment(alignment)
        storeCursorPos.mergeBlockFormat(textBlockFormat)
        self.qTextbrowser.setTextCursor(storeCursorPos)

    def writeTimeStamp(self):
        self.writeAppend(QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss:zzz"), Qt.AlignmentFlag.AlignCenter)

    def clear(self):
        self.qTextbrowser.clear()


    def sendData(self, ip_address:str, port:str, message:str):
        self.dataGram:QByteArray = message.encode('utf-8')
        if(port!=""):
            self.UdpSocket.writeDatagram(self.dataGram,
                                        QHostAddress(ip_address),
                                        int(port))
        else:
            self.writeAppend("Please enter the send port number",Qt.AlignmentFlag.AlignCenter)

    @pyqtSlot()
    def recvData(self):
        while(self.UdpSocket.hasPendingDatagrams()): 
            self.dataGram = QByteArray()
            self.dataGram.resize(self.UdpSocket.pendingDatagramSize())
            [tempbytes, _, _] = self.UdpSocket.readDatagram(self.dataGram.size())
            if(tempbytes!=None):
                self.writeTimeStamp()
                self.writeAppend(tempbytes.decode("utf-8"),Qt.AlignmentFlag.AlignLeft)
            else:
                self.writeAppend("Port Not Found",Qt.AlignmentFlag.AlignCenter)
        